package com.mmall.controller.portal;

import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.CookieUitl;
import com.mmall.util.JasonUtil;
import com.mmall.util.RedisShardedPoolUtil;
import com.mmall.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by root on 18-5-13.
 */
@Controller
@RequestMapping("/user/session/")
public class UserSessionController {

    @Autowired
    private IUserService iUserService;

    @ResponseBody
    @RequestMapping(value = "login.do", method = RequestMethod.GET)
    public ServerResponse login(HttpServletRequest request, HttpSession session, HttpServletResponse response, String username, String password){
        ServerResponse resp = iUserService.login(username, password);
        if (resp.isSuccess()){
            session.setAttribute(Const.CURRENT_USER, resp.getData());
        }
        return resp;
    }

    @ResponseBody
    @RequestMapping(value = "logout.do", method = RequestMethod.GET)
    public ServerResponse logout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccess();
    }

    @ResponseBody
    @RequestMapping(value = "get_user_info.do", method = RequestMethod.GET)
    public ServerResponse getUserInfo(HttpServletRequest request, HttpSession session){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if (user == null){
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(), "login first.");
        }
        return ServerResponse.createBySuccess(user);
    }


}
